package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 控制器助手类
 * Created by Lin on 2018/04/04.
 */
public final class ControllerHelper {

    private static final Map<Request, Handler> ACTION_MAP = new HashMap<Request, Handler>();
    static {
        Set<Class<?>> controllerMap = ClassHelper.getControllerClassSet();
        if(controllerMap != null && !controllerMap.isEmpty()) {
            for (Class<?> controllerClass : controllerMap) {
                Method[] methods = controllerClass.getDeclaredMethods();
                if(methods != null && methods.length > 0) {
                    for (Method method : methods) {
                        if(method.isAnnotationPresent(Action.class)){
                            String mapping = method.getAnnotation(Action.class).value();
                            if(mapping.matches("\\w+:/\\w*")) {
                                String[] mappings = mapping.split(":");
                                Request request = new Request(mappings[0], mappings[1]);
                                Handler handler = new Handler(controllerClass, method);
                                ACTION_MAP.put(request, handler);
                            }

                        }
                    }
                }
            }
        }
    }

    public static Handler getHandler(String requestMethod, String requestpath) {
        return ACTION_MAP.get(new Request(requestMethod, requestpath));
    }
}
